package com.eqdd.yiqidian.ui.base;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.util.SparseArray;
import android.widget.ImageView;
import android.widget.TextView;

import com.bigkoo.alertview.OnItemClickListener;
import com.bigkoo.pickerview.TimePickerView;
import com.eqdd.annotation.api.DataInjector;
import com.eqdd.yiqidian.R;
import com.eqdd.yiqidian.adapter.recycleadapter.ItemClickSupport;
import com.eqdd.yiqidian.adapter.slimadapter.SlimAdapterEx;
import com.eqdd.yiqidian.adapter.slimadapter.SlimInjector;
import com.eqdd.yiqidian.adapter.slimadapter.viewinjector.IViewInjector;
import com.eqdd.yiqidian.base.AppConstent;
import com.eqdd.yiqidian.base.BaseActivity;
import com.eqdd.yiqidian.base.Config;
import com.eqdd.yiqidian.bean.rebuild.slimedit.SlimEditApplyTitleBean;
import com.eqdd.yiqidian.bean.rebuild.slimedit.SlimEditBean;
import com.eqdd.yiqidian.bean.rebuild.slimedit.SlimEditChooseBean;
import com.eqdd.yiqidian.bean.rebuild.slimedit.SlimEditDividerBean;
import com.eqdd.yiqidian.bean.rebuild.slimedit.SlimEditEnterBean;
import com.eqdd.yiqidian.bean.rebuild.slimedit.SlimEditHintBean;
import com.eqdd.yiqidian.bean.rebuild.slimedit.SlimEditIconBean;
import com.eqdd.yiqidian.bean.rebuild.slimedit.SlimEditTimeBean;
import com.eqdd.yiqidian.bean.rebuild.slimedit.SlimEditVEnterBean;
import com.eqdd.yiqidian.box.ItemDecoration.SectionDividerItemDecoration;
import com.eqdd.yiqidian.utils.DensityUtil;
import com.eqdd.yiqidian.utils.ImageUtil;
import com.eqdd.yiqidian.utils.PicUtil;
import com.eqdd.yiqidian.utils.SPUtil;
import com.eqdd.yiqidian.widget.ActionSheetDialog;
import com.eqdd.yiqidian.widget.ChooseAlertView;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 * Created by lvzhihao on 17-7-19.
 */

public abstract class SlimBaseMultiEditActivity extends BaseActivity {

    private LinearLayoutManager mLinearLayoutManager;
    public SlimAdapterEx<SlimEditBean> slimAdapterEx;
    private SparseArray<TimePickerView> timePickers = new SparseArray<>();
    private SparseArray<ActionSheetDialog> chooseDialogs = new SparseArray<>();
    public List<SlimEditBean> datas = new ArrayList<>();
    public boolean isSave = true;
    public boolean isRead = true;
    protected boolean isDefautDivider = true;
    protected String msg;

    protected boolean checkParams() {
        for (int i = 0; i < slimAdapterEx.getData().size(); i++) {
            if (slimAdapterEx.getDataItem(i).isNeed()) {
                if (isParamBlank(i)) {
                    msg = "请输入" + slimAdapterEx.getDataItem(i).getTitle().replace("*", "").replace(" ", "");
                    return false;
                }
            }
        }
        return true;
    }

    protected String setParam(int i) {
        return TextUtils.isEmpty(slimAdapterEx.getData().get(i).getContent()) ? " " : slimAdapterEx.getData().get(i).getContent();
    }

    protected String setParamNull(int i) {
        return TextUtils.isEmpty(slimAdapterEx.getData().get(i).getContent()) ? null : slimAdapterEx.getData().get(i).getContent();
    }

    protected String dealText(String text) {
        return TextUtils.isEmpty(text) ? "" : text;
    }

    protected boolean isParamBlank(int pos) {
        return TextUtils.isEmpty(slimAdapterEx.getDataItem(pos).getContent()) && (slimAdapterEx.getDataItem(pos).getTag() == null);
    }

    @Override
    public void initData() {
        RecyclerView recyclerView = initRecyclerView();
        if (recyclerView == null) {
            System.out.println("recyclerView 未设置");
            return;
        }
        mLinearLayoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(mLinearLayoutManager);
        if (isDefautDivider) {
            recyclerView.addItemDecoration(new SectionDividerItemDecoration(this).setLeftPadding(DensityUtil.percentW(30)).setRightPadding(DensityUtil.percentW(30)));
        }
        recyclerView.setFocusable(false);
        slimAdapterEx = SlimAdapterEx.create().register(R.layout.item_edit_title_type, new SlimInjector<String>() {
            @Override
            public void onInject(String data, IViewInjector injector) {
                injector.text(R.id.tv_top_title, data);
            }
        })
                .register(R.layout.list_item_28, new SlimInjector<SlimEditHintBean>() {
                    @Override
                    public void onInject(SlimEditHintBean data, IViewInjector injector) {
                        injector.with(R.id.tv_left_content, view -> {
                            TextView textView = (TextView) view;
                            if (dealText(data.getTitle()).indexOf("*") == 0) {
                                SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(dealText(data.getTitle()));
                                ForegroundColorSpan foregroundColorSpan = new ForegroundColorSpan(Color.RED);

                                spannableStringBuilder.setSpan(foregroundColorSpan, 0, 1, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
                                textView.setText(spannableStringBuilder);
                            } else {
                                textView.setText(dealText(data.getTitle()));
                            }
                        })
                                .text(R.id.tv_right_hint_content, dealText(data.getContent()));
                    }
                })
                .register(R.layout.list_item_35, new SlimInjector<SlimEditApplyTitleBean>() {
                    @Override
                    public void onInject(SlimEditApplyTitleBean data, IViewInjector injector) {
                        injector.text(R.id.tv_upper_left_content, dealText(data.getTopLeftContent()))
                                .text(R.id.tv_upper_right_content, dealText(data.getTopRightContent()))
                                .text(R.id.tv_down_left_content, dealText(data.getTitle()))
                                .text(R.id.tv_down_right_content, dealText(data.getContent()));
                    }
                })
                .register(R.layout.list_item_29, new SlimInjector<SlimEditEnterBean>() {
                    @Override
                    public void onInject(SlimEditEnterBean data, IViewInjector injector) {
                        injector
                                .with(R.id.tv_left_content, view -> {
                                    TextView textView = (TextView) view;
                                    if (dealText(data.getTitle()).indexOf("*") == 0) {
                                        SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(dealText(data.getTitle()));
                                        ForegroundColorSpan foregroundColorSpan = new ForegroundColorSpan(Color.RED);

                                        spannableStringBuilder.setSpan(foregroundColorSpan, 0, 1, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
                                        textView.setText(spannableStringBuilder);
                                    } else {
                                        textView.setText(dealText(data.getTitle()));
                                    }
                                })
                                .text(R.id.tv_right_content, dealText(data.getContent()))
                                .with(R.id.tv_right_content, v -> ((TextView) v).setHint(dealText(data.getHintContent())));
                    }
                })
                .register(R.layout.list_item_44, new SlimInjector<SlimEditVEnterBean>() {
                    @Override
                    public void onInject(SlimEditVEnterBean data, IViewInjector injector) {
                        injector.with(R.id.tv_upper_content, view -> {
                            TextView textView = (TextView) view;
                            if (dealText(data.getTitle()).indexOf("*") == 0) {
                                SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(dealText(data.getTitle()));
                                ForegroundColorSpan foregroundColorSpan = new ForegroundColorSpan(Color.RED);

                                spannableStringBuilder.setSpan(foregroundColorSpan, 0, 1, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
                                textView.setText(spannableStringBuilder);
                            } else {
                                textView.setText(dealText(data.getTitle()));
                            }
                        })
                                .text(R.id.tv_down_content, dealText(data.getContent()))
                                .with(R.id.tv_down_content, v -> ((TextView) v).setHint(dealText(data.getHintContent())));
                    }
                })
                .register(R.layout.list_item_29, new SlimInjector<SlimEditTimeBean>() {
                    @Override
                    public void onInject(SlimEditTimeBean data, IViewInjector injector) {
                        injector.with(R.id.tv_left_content, view -> {
                            TextView textView = (TextView) view;
                            if (dealText(data.getTitle()).indexOf("*") == 0) {
                                SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(dealText(data.getTitle()));
                                ForegroundColorSpan foregroundColorSpan = new ForegroundColorSpan(Color.RED);

                                spannableStringBuilder.setSpan(foregroundColorSpan, 0, 1, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
                                textView.setText(spannableStringBuilder);
                            } else {
                                textView.setText(dealText(data.getTitle()));
                            }
                        })
                                .text(R.id.tv_right_content, dealText(data.getContent()))
                                .with(R.id.tv_right_content, v -> ((TextView) v).setHint(dealText(data.getHintContent())));
                    }
                })
                .register(R.layout.list_item_29, new SlimInjector<SlimEditChooseBean>() {
                    @Override
                    public void onInject(SlimEditChooseBean data, IViewInjector injector) {
                        injector.with(R.id.tv_left_content, view -> {
                            TextView textView = (TextView) view;
                            if (dealText(data.getTitle()).indexOf("*") == 0) {
                                SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(dealText(data.getTitle()));
                                ForegroundColorSpan foregroundColorSpan = new ForegroundColorSpan(Color.RED);

                                spannableStringBuilder.setSpan(foregroundColorSpan, 0, 1, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
                                textView.setText(spannableStringBuilder);
                            } else {
                                textView.setText(dealText(data.getTitle()));
                            }
                        })
                                .text(R.id.tv_right_content, dealText(data.getContent()))
                                .with(R.id.tv_right_content, v -> ((TextView) v).setHint(dealText(data.getHintContent())));
                    }
                })
                .register(R.layout.list_item_23, new SlimInjector<SlimEditIconBean>() {
                    @Override
                    public void onInject(SlimEditIconBean data, IViewInjector injector) {
                        injector.with(R.id.tv_left_content, view -> {
                            TextView textView = (TextView) view;
                            if (dealText(data.getTitle()).indexOf("*") == 0) {
                                SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(dealText(data.getTitle()));
                                ForegroundColorSpan foregroundColorSpan = new ForegroundColorSpan(Color.RED);

                                spannableStringBuilder.setSpan(foregroundColorSpan, 0, 1, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
                                textView.setText(spannableStringBuilder);
                            } else {
                                textView.setText(dealText(data.getTitle()));
                            }
                        })
                                .with(R.id.iv_right_logo, v -> {
                                    if (TextUtils.isEmpty(data.getContent())) {
                                        ImageUtil.setImage(data.getIcon(), (ImageView) v);
                                    } else if (!data.isCircle()) {
                                        ImageUtil.setImage(data.getContent(), (ImageView) v);
                                    } else {
                                        ImageUtil.setCircleImage(data.getContent(), (ImageView) v);
                                    }
                                });
                        if (data.isIconClicked()) {
                            injector.clicked(R.id.iv_right_logo, v -> PicUtil.previewSingle(SlimBaseMultiEditActivity.this, PicUtil.localMedia(data.getContent())));
                        }

                    }
                })
                .register(R.layout.list_item_32, new SlimInjector<SlimEditDividerBean>() {
                    @Override
                    public void onInject(SlimEditDividerBean data, IViewInjector injector) {
                    }
                }).attachTo(recyclerView);
        ItemClickSupport.addTo(recyclerView)
                .setOnItemClickListener((rv, position, v) -> {
                            SlimEditBean slimEditBean = slimAdapterEx.getData().get(position);
                            if (slimEditBean.isDeal()) {
                                itemClick(position);
                                return;
                            }
                            if (slimEditBean instanceof SlimEditHintBean) {
                                return;
                            } else if (slimEditBean instanceof SlimEditEnterBean) {
                                SlimEditEnterBean slimEditEnterBean = (SlimEditEnterBean) slimEditBean;
                                Bundle bundle = new Bundle();
                                bundle.putString("content", slimEditEnterBean.getContent());
                                bundle.putString("tip", TextUtils.isEmpty(slimEditEnterBean.getTip()) ? slimEditEnterBean.getTitle() : slimEditEnterBean.getTip());
                                bundle.putString("title", slimEditEnterBean.getTitle());
                                bundle.putBoolean("canBlank", slimEditEnterBean.isCanBlank());
                                bundle.putBoolean("onlyNumber", slimEditEnterBean.isNumber());
                                bundle.putBoolean("onlyInteger", slimEditEnterBean.isInteger());
                                AppConstent.schemes = slimEditEnterBean.getSchemes();
                                startActivityForResult(EditTextActivity.class, bundle, position);
                            } else if (slimEditBean instanceof SlimEditVEnterBean) {
                                SlimEditVEnterBean slimEditEnterBean = (SlimEditVEnterBean) slimEditBean;
                                Bundle bundle = new Bundle();
                                bundle.putString("content", slimEditEnterBean.getContent());
                                bundle.putString("tip", slimEditEnterBean.getTitle());
                                bundle.putString("title", slimEditEnterBean.getTitle());
                                bundle.putBoolean("canBlank", slimEditEnterBean.isCanBlank());
                                AppConstent.schemes = slimEditEnterBean.getSchemes();
                                startActivityForResult(EditTextActivity.class, bundle, position);
                            } else if (slimEditBean instanceof SlimEditTimeBean) {
                                SlimEditTimeBean slimEditTimeBean = (SlimEditTimeBean) slimEditBean;
                                TimePickerView timePickerView = timePickers.get(slimEditTimeBean.getPosition());
                                if (timePickerView == null) {
                                    timePickers.put(slimEditTimeBean.getPosition(), getTimePicker(slimEditTimeBean.getType(), (date, v1) -> {
                                        SimpleDateFormat sf = null;
                                        if (isBooleansE(slimEditTimeBean.getType(), Config.YEAR_MONTH_DAY_TYPE)) {
                                            sf = new SimpleDateFormat("yyyy-MM-dd");
                                        } else if (isBooleansE(slimEditTimeBean.getType(), Config.YEAR_MONTH_DAY_HOUR_TYPE)) {
                                            sf = new SimpleDateFormat("yyyy-MM-dd HH");
                                        } else if (isBooleansE(slimEditTimeBean.getType(), Config.ALL_TYPE)) {
                                            sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                        } else if (isBooleansE(slimEditTimeBean.getType(), Config.YEAR_MONTH_DAY_HOUR_MINITE_TYPE)) {
                                            sf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                                        }
                                        if (!onTimeClickBefore(position, sf.format(date))) {
                                            slimEditTimeBean.setContent(sf.format(date));
                                            slimAdapterEx.notifyItemChanged(position);
                                        }
                                        onTimeClick(position);
                                    }));
                                    timePickerView = timePickers.get(slimEditTimeBean.getPosition());
                                }
                                timePickerView.show();
                            } else if (slimEditBean instanceof SlimEditChooseBean) {
                                SlimEditChooseBean slimEditChooseBean = (SlimEditChooseBean) slimEditBean;
                                ActionSheetDialog chooseDialog = chooseDialogs.get(slimEditChooseBean.getPosition());
                                if (chooseDialog == null) {
                                    chooseDialogs.put(slimEditChooseBean.getPosition(), getBottomChoose(slimEditChooseBean.getItems(), (o, pos) -> {
                                        if (position >= 1) {
                                            if (!onChooseClickBefore(position, slimEditChooseBean.getItems()[pos - 1])) {
                                                slimEditChooseBean.setContent(slimEditChooseBean.getItems()[pos - 1]);
                                                slimAdapterEx.notifyItemChanged(position);
                                            }
                                            onChooseClick(position);
                                        }
                                    }));
                                    chooseDialog = chooseDialogs.get(slimEditChooseBean.getPosition());
                                }
                                chooseDialog.show();
                            }
                            itemClick(position);
                        }

                );
    }

    protected boolean onChooseClickBefore(int position, String s) {
        return false;
    }

    /**
     * 选择时间后,更新界面之前
     *
     * @param position
     * @param format
     * @return 返回true 表示自己更新界面,返回false 立即更新界面
     */
    protected boolean onTimeClickBefore(int position, String format) {
        return false;
    }

    protected void onTimeClick(int position) {

    }

    private boolean isBooleansE(boolean[] b1, boolean[] b2) {
        if (b1.length == b2.length) {
            for (int i = 0; i < b1.length; i++) {
                if (b1[i] != b2[i]) {
                    return false;
                }
            }
            return true;
        }
        return false;
    }

    protected void onChooseClick(int position) {

    }


    private TimePickerView getTimePicker(boolean[] type, TimePickerView.OnTimeSelectListener onTimeSelectListener) {
        TimePickerView pvDayTime = new TimePickerView.Builder(this, onTimeSelectListener)
                .setOutSideCancelable(true)
                .setType(type)
                .setDate(Calendar.getInstance())
                .setRange(1900, 2050)
                .build();
        return pvDayTime;
    }

    private ActionSheetDialog getBottomChoose(String[] chooseTexts, OnItemClickListener onItemClickListener) {
        ActionSheetDialog bottomChoose = ChooseAlertView.getBottomChoose(this, "请选择", chooseTexts,
                onItemClickListener);
        return bottomChoose;
    }


    protected abstract RecyclerView initRecyclerView();

    public abstract void itemClick(int p);

    @Override
    public void setView() {

        setEditBeans();
        if (isRead) {
            recoverData();
        }
        recoverAfter();
        slimAdapterEx.updateData(datas);
        loadNetData();
    }

    protected void loadNetData() {

    }

    protected void recoverAfter() {

    }

    protected abstract void setEditBeans();

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Config.INTENT_CONTENT) {
            String content = data.getStringExtra("content");
            datas.get(requestCode).setContent(content);
            slimAdapterEx.notifyItemChanged(requestCode);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (isSave) {
            saveData();
        }
    }

    public void saveData() {
        if (datas != null) {
            SPUtil.setParam(getLocalClassName() + user.getUname(), datas);
        }
        DataInjector.saveData(this);
    }

    public void recoverData() {
        if (isRead) {
            List<SlimEditBean> data = (List<SlimEditBean>) SPUtil.getParam(getLocalClassName() + user.getUname());
            if (data != null) {
                datas.clear();
                datas.addAll(data);
                DataInjector.recoverData(this);
            }
        }
    }

    public void clearData() {
        isSave = false;
        SPUtil.setParam(getLocalClassName() + user.getUname(), Config.NULL);
        DataInjector.clearData(this);
    }
}
